package com.newly.driver.sdk.device.video.service.impl.qiniu;

import cn.hutool.core.lang.Assert;
import cn.hutool.json.JSONObject;
import com.newly.driver.sdk.device.video.cloud.stream.QueryLiveStreamReq;
import com.newly.driver.sdk.device.video.cloud.stream.QueryLiveStreamResp;
import com.newly.driver.sdk.device.video.constants.DeviceConstant;
import com.newly.driver.sdk.device.video.exception.NewlyDeviceException;
import com.newly.driver.sdk.device.video.service.api.IStream;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.qvs.model.DynamicLiveRoute;
import lombok.extern.slf4j.Slf4j;

/**
 * @author gjm guan
 * @date 2021/10/21 15:33
 * @desc 七牛平台
 */
@Slf4j
public class QiNiuStream extends AbstractQiNiuCloud implements IStream {
    @Override
    public QueryLiveStreamResp queryLiveStream(QueryLiveStreamReq queryLiveStreamReq) {
        try {
            Assert.notNull(queryLiveStreamReq, "查询直播流数据异常");
            Assert.notBlank(queryLiveStreamReq.getDeviceId(), "deviceId不能为空");
            Assert.notBlank(queryLiveStreamReq.getChannelId(), "channelId不能为空");
        } catch (IllegalArgumentException e) {
            throw new NewlyDeviceException(e.getMessage());
        }

        // 得到流id
        String streamId = this.handlerStreamId(queryLiveStreamReq.getDeviceId(), queryLiveStreamReq.getChannelId());

        DynamicLiveRoute dynamicLiveRoute = new DynamicLiveRoute(this.publishIP, this.playIP, DeviceConstant.STREAM_LIVE_EXPIRE_TIME);
        Response resp = null;
        try {
            resp = this.getStreamManager().dynamicPublishPlayURL(this.namespaceId, streamId, dynamicLiveRoute);
        } catch (QiniuException e) {
            e.printStackTrace();
        }

        // 解析响应数据
        JSONObject jsonObject = this.parseMap(resp);
        QueryLiveStreamResp queryLiveStreamResp = new QueryLiveStreamResp(jsonObject);

        return queryLiveStreamResp;
    }
}
